package com.linzm.leetcode.primary.哈希表.有效的字母异位词;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zimingl
 * @Date 2022/10/6 22:10
 * @Description: TODO
 */
public class 哈希表242有效的字母异位词 {

    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        char[] str1 = s.toCharArray();
        char[] str2 = t.toCharArray();
        Arrays.sort(str1);
        Arrays.sort(str2);
        return Arrays.equals(str1, str2);
    }

    public boolean isAnagram2(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] table = new int[26];
        for (int i = 0; i < s.length(); i++) {
            table[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < t.length(); i++) {
            table[t.charAt(i) - 'a']--;
            if (table[t.charAt(i) - 'a'] < 0) {
                return false;
            }
        }
        return true;
    }

    @Test
    public void test2(){
        String s = "aacc", t = "ccac";
        System.out.println( isAnagram3(s, t) );
    }

    public boolean isAnagram3(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        char[] sChars = s.toCharArray();
        char[] tChars = t.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (char ch: sChars){
            int count  = map.getOrDefault(ch, 0) + 1;
            map.put(ch, count);
        }
        for (char ch : tChars){
            int count = map.getOrDefault(ch, 0);
            if (count > 0){
                count --;
            }
            if (count > 0){
                map.put(ch, count);
            } else {
                map.remove(ch);
            }
        }
        if (map.keySet().size() > 0){
            return false;
        }
        return true;
    }
}
